<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 多线程1). 多线程类似于同时执行多个不同程序，多线程运行有如下优点：  使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人，这样比如用户点击了一个按钮去触发某些事件的处理，可以弹出一个进度条来显示处理的进度 程序的运行速度可能加快 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等，线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Python-学习(九)--多线程">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Python/Python-学习(九)--多线程/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 多线程1). 多线程类似于同时执行多个不同程序，多线程运行有如下优点：  使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人，这样比如用户点击了一个按钮去触发某些事件的处理，可以弹出一个进度条来显示处理的进度 程序的运行速度可能加快 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等，线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-979ed67e468b4473.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-890154d7d6364c3e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-9e6776715cab799a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-cee54140aedf6e84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:31:58.857Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python-学习(九)--多线程">
<meta name="twitter:description" content="####1. 多线程1). 多线程类似于同时执行多个不同程序，多线程运行有如下优点：  使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人，这样比如用户点击了一个按钮去触发某些事件的处理，可以弹出一个进度条来显示处理的进度 程序的运行速度可能加快 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等，线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-979ed67e468b4473.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Python/Python-学习(九)--多线程/"/>





  <title>Python-学习(九)--多线程 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Python/Python-学习(九)--多线程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python-学习(九)--多线程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 多线程<br>1). 多线程类似于同时执行多个不同程序，多线程运行有如下优点：</p>
<ul>
<li>使用线程可以把占据长时间的程序中的任务放到后台去处理。</li>
<li>用户界面可以更加吸引人，这样比如用户点击了一个按钮去触发某些事件的处理，可以弹出一个进度条来显示处理的进度</li>
<li>程序的运行速度可能加快</li>
<li>在一些等待的任务实现上如用户输入、文件读写和网络收发数据等，线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。<a id="more"></a>
</li>
</ul>
<p>2). 线程在执行过程中与进程还是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行，必须依存在应用程序中，由应用程序提供多个线程执行控制。<br>每个线程都有他自己的一组CPU寄存器，称为线程的上下文，该上下文反映了线程上次运行该线程的CPU寄存器的状态。<br>指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器，线程总是在进程得到上下文中运行的，这些地址都用于标志拥有线程的进程地址空间中的内存。</p>
<ul>
<li>线程可以被抢占（中断）。<ul>
<li>在其他线程正在运行时，线程可以暂时搁置（也称为睡眠） – 这就是线程的退让。</li>
</ul>
</li>
</ul>
<p>3). 线程可以分为:</p>
<ul>
<li>内核线程：由操作系统内核创建和撤销。</li>
<li>用户线程：不需要内核支持而在用户程序中实现的线程。</li>
</ul>
<p>4). Python3 线程中常用的两个模块为：</p>
<ul>
<li>_thread</li>
<li>threading(推荐使用)<br>thread 模块已被废弃。用户可以使用 threading 模块代替。所以，在 Python3 中不能再使用”thread” 模块。为了兼容性，Python3 将 thread 重命名为 “_thread”。</li>
</ul>
<p>####2. 创建新线程<br>Python中使用线程有两种方式：函数或者用类来包装线程对象。<br>函数式：调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">_thread.start_new_thread ( function, args[, kwargs] )</span><br></pre></td></tr></table></figure></p>
<p>参数说明:</p>
<ul>
<li>function - 线程函数。</li>
<li>args - 传递给线程函数的参数,他必须是个tuple类型。</li>
<li>kwargs - 可选参数。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">import _thread</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line"># 为线程定义一个函数</span><br><span class="line">def print_time(threadName, delay):</span><br><span class="line">	count = 0</span><br><span class="line">	while count &lt; 5:</span><br><span class="line">		time.sleep(delay)</span><br><span class="line">		count += 1</span><br><span class="line">		print(&quot;%s: %s&quot; % (threadName, time.ctime(time.time())))</span><br><span class="line">		pass</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line"># 创建两个线程</span><br><span class="line">try:</span><br><span class="line">	_thread.start_new_thread(print_time, (&quot;Thread-1&quot;,2))</span><br><span class="line">	_thread.start_new_thread(print_time, (&quot;Thread-2&quot;,4))</span><br><span class="line">	pass</span><br><span class="line">except Exception as e:</span><br><span class="line">	print(&quot;Error: 无法启动线程&quot;)</span><br><span class="line">	raise e</span><br><span class="line"></span><br><span class="line">while 1:</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-979ed67e468b4473.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>####3. 线程模块<br>Python3 通过两个标准库 _thread 和 threading 提供对线程的支持。<br>_thread 提供了低级别的、原始的线程以及一个简单的锁，它相比于 threading 模块的功能还是比较有限的。<br>threading 模块除了包含 _thread 模块中的所有方法外，还提供的其他方法：</p>
<ul>
<li>threading.currentThread(): 返回当前的线程变量。</li>
<li>threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前，不包括启动前和终止后的线程。</li>
<li>threading.activeCount(): 返回正在运行的线程数量，与len(threading.enumerate())有相同的结果。</li>
</ul>
<p>除了使用方法外，线程模块同样提供了Thread类来处理线程，Thread类提供了以下方法:</p>
<ul>
<li>run(): 用以表示线程活动的方法。</li>
<li>start():启动线程活动。</li>
<li>join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。</li>
<li>isAlive(): 返回线程是否活动的。</li>
<li>getName(): 返回线程名。</li>
<li>setName(): 设置线程名。</li>
</ul>
<p>####4. 使用 threading 模块创建线程<br>从 threading.Thread 继承创建一个新的子类，并实例化后调用 start() 方法启动新线程，即它调用了线程的 run() 方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">import threading</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">exitFlag = 0</span><br><span class="line">class myThread(threading.Thread):</span><br><span class="line">	&quot;&quot;&quot;docstring for myThread&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, threadID,name,counter):</span><br><span class="line">		super(myThread, self).__init__()</span><br><span class="line">		self.threadID = threadID</span><br><span class="line">		self.name = name</span><br><span class="line">		self.counter = counter</span><br><span class="line">	def run(self):</span><br><span class="line">		print(&quot;开始线程: &quot; + self.name)</span><br><span class="line">		print_time(self.name, self.counter, 5)</span><br><span class="line">		print(&quot;退出线程: &quot; + self.name)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">def print_time(threadName, delay, counter):</span><br><span class="line">	while counter:</span><br><span class="line">		if exitFlag:</span><br><span class="line">			threadName.exit()</span><br><span class="line">			pass</span><br><span class="line">		time.sleep(delay)</span><br><span class="line">		print(&quot;%s: %s&quot; % (threadName, time.ctime(time.time())))</span><br><span class="line">		counter -= 1</span><br><span class="line">		pass</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line"># 创建新线程</span><br><span class="line">thread1 = myThread(1, &quot;Thread-1&quot;, 1)</span><br><span class="line">thread2 = myThread(2, &quot;Thread-2&quot;, 2)</span><br><span class="line"></span><br><span class="line"># 开启新线程</span><br><span class="line">thread1.start()</span><br><span class="line">thread2.start()</span><br><span class="line">thread1.join()</span><br><span class="line">thread2.join()</span><br><span class="line"></span><br><span class="line">print(&quot;退出主线程&quot;)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-890154d7d6364c3e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####5. 线程同步<br>如果多个线程共同对某个数据修改，则可能出现不可预料的结果，为了保证数据的正确性，需要对多个线程进行同步。<br>使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步，这两个对象都有 acquire 方法和 release 方法，对于那些需要每次只允许一个线程操作的数据，可以将其操作放到 acquire 和 release 方法之间。如下：<br>多线程的优势在于可以同时运行多个任务（至少感觉起来是这样）。但是当线程需要共享数据时，可能存在数据不同步的问题。<br>考虑这样一种情况：一个列表里所有元素都是0，线程”set”从后向前把所有元素改成1，而线程”print”负责从前往后读取列表并打印。<br>那么，可能线程”set”开始改的时候，线程”print”便来打印列表了，输出就成了一半0一半1，这就是数据的不同步。为了避免这种情况，引入了锁的概念。<br>锁有两种状态——锁定和未锁定。每当一个线程比如”set”要访问共享数据时，必须先获得锁定；如果已经有别的线程比如”print”获得锁定了，那么就让线程”set”暂停，也就是同步阻塞；等到线程”print”访问完毕，释放锁以后，再让线程”set”继续。经过这样的处理，打印列表时要么全部输出0，要么全部输出1，不会再出现一半0一半1的尴尬场面。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">import threading</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">class myThread(threading.Thread):</span><br><span class="line">	&quot;&quot;&quot;docstring for myThread&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, threadID, name, counter):</span><br><span class="line">		super(myThread, self).__init__()</span><br><span class="line">		self.threadID = threadID</span><br><span class="line">		self.name = name</span><br><span class="line">		self.counter = counter</span><br><span class="line">	def run(self):</span><br><span class="line">		print(&quot;开启线程：&quot; + self.name)</span><br><span class="line">		# 获取锁，用于线程同步</span><br><span class="line">		threadLock.acquire()</span><br><span class="line">		print_time(self.name, self.counter, 3)</span><br><span class="line">		# 释放锁，开启下一个线程</span><br><span class="line">		threadLock.release()</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">def print_time(threadName, delay, counter):</span><br><span class="line">	while counter:</span><br><span class="line">		time.sleep(delay)</span><br><span class="line">		print(&quot;%s: %s&quot; % (threadName, time.ctime(time.time())))</span><br><span class="line">		counter -= 1</span><br><span class="line">		pass</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">threadLock = threading.Lock()</span><br><span class="line">threads = []</span><br><span class="line"></span><br><span class="line"># 创建新线程</span><br><span class="line">thread1 = myThread(1, &quot;Thread-1&quot;, 1)</span><br><span class="line">thread2 = myThread(2, &quot;Thread-2&quot;, 2)</span><br><span class="line"></span><br><span class="line"># 开启新线程</span><br><span class="line">thread1.start()</span><br><span class="line">thread2.start()</span><br><span class="line"></span><br><span class="line"># 添加线程到线程列表</span><br><span class="line">threads.append(thread1)</span><br><span class="line">threads.append(thread2)</span><br><span class="line"></span><br><span class="line"># 等待所有线程完成</span><br><span class="line">for t in threads:</span><br><span class="line">	t.join()</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">print(&quot;退出线程&quot;)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-9e6776715cab799a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>####6. 线程优先级队列（ Queue）<br>Python 的 Queue 模块中提供了同步的、线程安全的队列类，包括FIFO（先入先出)队列Queue，LIFO（后入先出）队列LifoQueue，和优先级队列 PriorityQueue。<br>这些队列都实现了锁原语，能够在多线程中直接使用，可以使用队列来实现线程间的同步。<br><strong>Queue 模块中的常用方法:</strong></p>
<ul>
<li>Queue.qsize() 返回队列的大小</li>
<li>Queue.empty() 如果队列为空，返回True,反之False</li>
<li>Queue.full() 如果队列满了，返回True,反之False</li>
<li>Queue.full 与 maxsize 大小对应</li>
<li>Queue.get([block[, timeout]])获取队列，timeout等待时间</li>
<li>Queue.get_nowait() 相当Queue.get(False)</li>
<li>Queue.put(item) 写入队列，timeout等待时间</li>
<li>Queue.put_nowait(item) 相当Queue.put(item, False)</li>
<li>Queue.task_done() 在完成一项工作之后，Queue.task_done()函数向任务已经完成的队列发送一个信号</li>
<li>Queue.join() 实际上意味着等到队列为空，再执行别的操作<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line">import queue</span><br><span class="line">import threading</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">exitFlag = 0</span><br><span class="line"></span><br><span class="line">class myThread(threading.Thread):</span><br><span class="line">	&quot;&quot;&quot;docstring for myThread&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, threadID, name, q):</span><br><span class="line">		super(myThread, self).__init__()</span><br><span class="line">		self.threadID = threadID</span><br><span class="line">		self.name = name</span><br><span class="line">		self.q = q</span><br><span class="line">	def run(self):</span><br><span class="line">		print(&quot;开启线程：&quot; + self.name)</span><br><span class="line">		process_data(self.name, self.q)</span><br><span class="line">		print(&quot;退出线程：&quot; + self.name)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">def process_data(threadName, q):</span><br><span class="line">	while not exitFlag:</span><br><span class="line">		queueLock.acquire()</span><br><span class="line">		if not workQueue.empty():</span><br><span class="line">			data = q.get()</span><br><span class="line">			queueLock.release()</span><br><span class="line">			print(&quot;%s processing %s&quot; % (threadName, data))</span><br><span class="line">			pass</span><br><span class="line">		else:</span><br><span class="line">			queueLock.release()</span><br><span class="line">		pass</span><br><span class="line">		time.sleep(1)</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">threadList = [&quot;Thread-1&quot;, &quot;Thread-2&quot;, &quot;Thread-3&quot;]</span><br><span class="line">nameList = [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;, &quot;Five&quot;]</span><br><span class="line">queueLock = threading.Lock()</span><br><span class="line">workQueue = queue.Queue(10)</span><br><span class="line">threads = []</span><br><span class="line">threadID = 1</span><br><span class="line"></span><br><span class="line"># 创建新线程</span><br><span class="line">for tName in threadList:</span><br><span class="line">	thread = myThread(threadID, tName, workQueue)</span><br><span class="line">	thread.start()</span><br><span class="line">	threads.append(thread)</span><br><span class="line">	threadID += 1</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line"># 填充队列</span><br><span class="line">queueLock.acquire()</span><br><span class="line">for word in nameList:</span><br><span class="line">	workQueue.put(word)</span><br><span class="line">	pass</span><br><span class="line">queueLock.release()</span><br><span class="line"></span><br><span class="line"># 等待队列清空</span><br><span class="line">while not workQueue.empty():</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line"># 通知线程退出</span><br><span class="line">exitFlag = 1</span><br><span class="line"></span><br><span class="line"># 等待所有线程完成</span><br><span class="line">for t in threads:</span><br><span class="line">	t.join()</span><br><span class="line">	pass</span><br><span class="line">print(&quot;退出主线程&quot;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-cee54140aedf6e84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(三)/" rel="next" title="Python-学习(三)">
                <i class="fa fa-chevron-left"></i> Python-学习(三)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(二)/" rel="prev" title="Python-学习(二)">
                Python-学习(二) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
